package com.ebt.m.jpush;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import com.ebt.m.AppContext;
import com.ebt.m.AppInitService;
import com.ebt.m.BuildConfig;
import com.ebt.m.activity.MainActivity;
import com.ebt.m.activity.utils.WebBaseActivityUtil;
import com.ebt.m.commons.utils.Logger;
import com.ebt.m.commons.utils.SystemUtil;
import com.ebt.m.data.rxModel.api.MsgAPI;
import com.ebt.m.msgnote.MsgConstant;
import com.ebt.m.msgnote.bean.TypeMsgItems;
import com.ebt.m.utils.GsonUtil;

import org.json.JSONException;
import org.json.JSONObject;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * JPush Handler
 * Created by archer.qi on 2016/6/6.
 */
public class DoJPush {

    // JPush返回类型
    public static final int JPush_Type_Notification = 0x00000000; // 通知
    public static final int JPush_Type_Message = 0x00000001; // 消息
    public static final int JPush_Type_Click = 0x00000002; // 点击通知栏
    public static final int JPush_Type_RegisterID = 0x00000003; // 获取注册ID

    // JPush消息接收处理
    public static void doJPushReceived(int type, Bundle bundle) {
        switch (type) {
            case JPush_Type_Notification:
                break;
            case JPush_Type_Message:
                JPushResult result = JPushData.getJPushResult(bundle);
                result.pushType = type;
                JPushUtil.updateJPushListeners(result);
                break;
            case JPush_Type_Click:
                JPushResult result1 = JPushData.getJPushResult(bundle);
                doJPushNotificationClick(result1);
                break;
            case JPush_Type_RegisterID:
                // 暂时不用RegisterID
                break;
            default:
                break;
        }
    }

    /**
     * 点击消息通知事件
     *
     * @param result
     */
    public static void doJPushNotificationClick(JPushResult result) {
        if (!SystemUtil.isAppAlive(BuildConfig.APPLICATION_ID)) {
            startApp();
        } else {
            try {
                JSONObject object = new JSONObject(result.extra);
                if (object.has("topic")) {
                    agentStatusValidate(object);
                } else {
                    gotoMsgDetail(result.extra);
                }
            } catch (Exception e) {
                Logger.e(e);
            }
        }
    }

    private static void startApp() {
        Context context = AppContext.getInstance();
        Intent launchIntent = context.getPackageManager().
                getLaunchIntentForPackage(BuildConfig.APPLICATION_ID);
        launchIntent.setFlags(
                Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
        context.startActivity(launchIntent);
    }

    private static void agentStatusValidate(JSONObject object) throws JSONException {
        String topic = object.getString("topic");
        if (topic.equals(JPushUtil.TOPIC_CHANGEAGENTVALIDATESTATUS)) {
            int status = object.getJSONObject("dataJson").getInt("status");
            if (status == 1) {
                Intent intent = new Intent(AppContext.getInstance(), MainActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                AppContext.getInstance().startActivity(intent);
            }
        }
    }

    private static void gotoMsgDetail(String jsonData) {
        try {
            TypeMsgItems.TypeMsg bean = GsonUtil.parseJsonWithGson(jsonData, TypeMsgItems.TypeMsg.class);
            if (bean.getJumpMode() == MsgConstant.JUMP_MODE_URL) {
                Context context = AppContext.getInstance();
                WebBaseActivityUtil.gotoWeb(context, false, bean.getTitle(), bean.getUrl(), false, true);
                readMsg(bean.getMessageId());
            } else if (bean.getJumpMode() == MsgConstant.JUMP_MODE_APP) {

            } else {

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void readMsg(int msgId) {
        MsgAPI opportunityApi = AppInitService.getMsgApi();
        opportunityApi.readMsg(msgId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    Logger.i(msgId + " is readed");
                }, throwable -> {
                    throwable.printStackTrace();
                });
    }

}
